package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ICompanyCustomGroupingDAO;
import org.jsola.hr.dto.CompanyCustomGroupingAddDTO;
import org.jsola.hr.dto.CompanyCustomGroupingUpdateDTO;
import org.jsola.hr.entity.CompanyCustomGroupingDO;
import org.jsola.hr.query.CompanyCustomGroupingQuery;
import org.jsola.hr.service.ICompanyCustomGroupingService;
import org.jsola.hr.vo.CompanyCustomGroupingListVO;
import org.jsola.hr.vo.CompanyCustomGroupingVO;
import org.jsola.salary.common.CalendarKit;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义用工单位分组
 *
 * @author zhr
 */
@Service("hrCompanyCustomGroupingServiceImpl")
public class CompanyCustomGroupingServiceImpl implements ICompanyCustomGroupingService {

    @Autowired
    private ICompanyCustomGroupingDAO companyCustomGroupingDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public CompanyCustomGroupingVO save(CompanyCustomGroupingAddDTO companyCustomGroupingAddDTO, TokenUser tokenUser) {
        // 转DO
        CompanyCustomGroupingDO companyCustomGroupingDO = companyCustomGroupingAddDTO.to(CompanyCustomGroupingDO.class);
        // 保存
        companyCustomGroupingDO = save(companyCustomGroupingDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return companyCustomGroupingDO.to(CompanyCustomGroupingVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(CompanyCustomGroupingUpdateDTO companyCustomGroupingUpdateDTO, TokenUser tokenUser) {
        //转DO
        CompanyCustomGroupingDO companyCustomGroupingDO = companyCustomGroupingUpdateDTO.to(CompanyCustomGroupingDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(companyCustomGroupingDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, Long... companyCustomGroupingIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) companyCustomGroupingIds);
    }


    @Override
    public CompanyCustomGroupingVO selectById(Long companyCustomGroupingId, String siteId) {
        CompanyCustomGroupingDO companyCustomGroupingDO = selectDOById(companyCustomGroupingId, siteId);
        if (companyCustomGroupingDO == null) {
            return null;
        }
        return companyCustomGroupingDO.to(CompanyCustomGroupingVO.class);
    }

    @Override
    public List<CompanyCustomGroupingListVO> select(CompanyCustomGroupingQuery companyCustomGroupingQuery, String siteId) {
        List<CompanyCustomGroupingDO> companyCustomGroupingDOList = selectDO(companyCustomGroupingQuery, siteId);
        if (CollectionUtils.isEmpty(companyCustomGroupingDOList)) {
            return companyCustomGroupingDOList == null ? null : new ArrayList<>();
        }
        return companyCustomGroupingDOList.stream()
                .map(companyCustomGroupingDO -> companyCustomGroupingDO.to(CompanyCustomGroupingListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(CompanyCustomGroupingQuery companyCustomGroupingQuery, String siteId) {
        Example example = buildExample(companyCustomGroupingQuery, siteId);
        return companyCustomGroupingDAO.selectCountByExample(example);
    }

    @Override
    public Page<CompanyCustomGroupingListVO> selectPage(CompanyCustomGroupingQuery companyCustomGroupingQuery, String siteId) {
        Example example = buildExample(companyCustomGroupingQuery, siteId);
        Page<CompanyCustomGroupingDO> page = companyCustomGroupingDAO.selectPageByExample(example,
                companyCustomGroupingQuery.getPageNo(),
                companyCustomGroupingQuery.getPageSize());

        return page.to(CompanyCustomGroupingListVO.class);
    }

    @Override
    public CompanyCustomGroupingDO selectDOById(Long companyCustomGroupingId, String siteId) {
        return listById(companyCustomGroupingId, siteId);
    }

    @Override
    public List<CompanyCustomGroupingDO> selectDO(CompanyCustomGroupingQuery companyCustomGroupingQuery, String siteId) {
        Example example = buildExample(companyCustomGroupingQuery, siteId);
        return companyCustomGroupingDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public List<CompanyCustomGroupingDO> selectAndSaveBySiteAndMonthly(Integer yearly, Integer monthly, String moduleCode, TokenUser tokenUser) {
        Example example = new Example(CompanyCustomGroupingDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("yearly", yearly)
                .andEqualTo("monthly", monthly)
                .andEqualTo("createUserId", tokenUser.getUserId());
        example.orderBy("gmtCreate").desc();
        List<CompanyCustomGroupingDO> companyCustomGroupingDOList = companyCustomGroupingDAO.selectByExample(example);
        // 本月分组为空 取上个月的新建一份
        if (CollectionUtils.isEmpty(companyCustomGroupingDOList)) {
            Calendar lastMonth = CalendarKit.getLastMonth(yearly, monthly);
            Integer lastYearly = lastMonth.get(Calendar.YEAR);
            Integer lastMonthly = lastMonth.get(Calendar.MONTH) + 1;
            example = new Example(CompanyCustomGroupingDO.class);
            example.and()
                    .andEqualTo("valid", true)
                    .andEqualTo("siteId", tokenUser.getSiteId())
                    .andEqualTo("yearly", lastYearly)
                    .andEqualTo("monthly", lastMonthly)
                    .andEqualTo("createUserId", tokenUser.getUserId());
            example.orderBy("gmtCreate").desc();
            List<CompanyCustomGroupingDO> lastDOList = companyCustomGroupingDAO.selectByExample(example);
            if (CollectionUtils.isEmpty(lastDOList)) {
                return new ArrayList<>();
            }
            // 用上个月的分组创建这个月的
            for (CompanyCustomGroupingDO companyCustomGroupingDO : lastDOList) {
                CompanyCustomGroupingAddDTO companyCustomGroupingAddDTO = companyCustomGroupingDO.to(CompanyCustomGroupingAddDTO.class);
                companyCustomGroupingAddDTO.setYearly(yearly);
                companyCustomGroupingAddDTO.setMonthly(monthly);
                CompanyCustomGroupingVO companyCustomGroupingVO = save(companyCustomGroupingAddDTO, tokenUser);
                companyCustomGroupingDOList.add(companyCustomGroupingVO.to(CompanyCustomGroupingDO.class));
            }
        }
        return companyCustomGroupingDOList;
    }


    /**
     * 根据查询参数，构建example
     *
     * @param companyCustomGroupingQuery 查询参数
     * @param siteId                     所属站点id
     * @return example
     */
    private Example buildExample(CompanyCustomGroupingQuery companyCustomGroupingQuery, String siteId) {
        Example example = new Example(CompanyCustomGroupingDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        ExampleKit.setExampleOrder(example, companyCustomGroupingQuery.getOrders());
        return example;
    }
}




